import moment from 'moment'
import { ReceivedData as ContactReceived, ContactSerializer } from './ContactSerializer'
import { OrderItemSerializer } from './OrderItemSerializer'
import { ContactModel } from '~/model/ContactModel'
import { OrderModel } from '~/model/OrderModel'
import { contactFromId } from '~/model/utils'

export abstract class OrderSerializer {
  static serialize(model: OrderModel): SentData {
    if (!model.consumer) {
      throw new Error(`OrderSerializer.serialize: model.consumer => ${model.consumer}`)
    }
    return {
      consumerId: model.consumer?.id,
      era: model.era,
      batch: model.batch,
      date: moment(model.date).format('YYYY-MM-DD HH:mm:ss'),
      needDelivery: model.needDelivery,
      deliveryPersonId: model.deliveryPerson ? model.deliveryPerson.id : null,
      receiver: model.receiver,
      fare: model.fare,
      invalid: model.invalid,
      settled: model.settled,
      notes: model.notes,
      items: model.items.map(x => OrderItemSerializer.serialize(x)),
    }
  }

  static async deserialize(data: ReceivedData): Promise<OrderModel> {
    const model = new OrderModel()
    model.id = data.id
    // model.consumer
    model.consumer = ContactSerializer.deserialize(data.consumer)
    // model.consumer = await contactFromId(data.consumerId)
    model.era = data.era
    model.batch = data.batch
    model.date = new Date(data.date)

    model.needDelivery = data.needDelivery
    model.deliveryPerson = data.deliveryPersonId ? await contactFromId(data.deliveryPersonId) : undefined
    model.receiver = data.receiver
    model.fare = data.fare

    model.invalid = data.invalid
    model.settled = data.settled
    model.notes = data.notes
    model.stub = data.stub || undefined

    model.items = await Promise.all(data.items.map(x => OrderItemSerializer.deserialize(x)))
    return model
  }
}

interface SentData {
  consumerId: number
  era: number,
  batch: number
  date: string
  needDelivery: boolean
  deliveryPersonId: number | null
  receiver: string
  fare: number
  invalid: boolean
  settled: boolean
  notes: string
  items: any
}

interface ReceivedData {
  id: number
  consumerId: number
  consumer: ContactReceived
  era: number,
  batch: number
  date: string
  needDelivery: boolean
  deliveryPersonId: number | null
  receiver: string
  fare: number
  invalid: boolean
  settled: boolean
  notes: string
  stub: string | null
  items: any
}
